var express = require("express");
var router = express.Router();
var moment = require("moment");
var md5 = require("md5-node");
var vertoken = require("../token/token");
const { Op } = require("sequelize");
const User = require("../db/model/userModel");
const Role = require("../db/model/userModel");
const { fail, successWithData } = require("../utils/result");

/**
 * 登陆接口
 * @api {POST} /user/login 登陆接口
 * @apiDescription 登陆接口
 * @apiName login
 * @apiBody {String} username="admin"   用户名
 * @apiBody {String} password="123456"   密码
 * @apiParamExample {json} Request-Example:
 *     {
 *        "username": "admin",
 *        "password": "123456"
 *     }
 * @apiGroup User
 * @apiVersion 1.0.0
 */
router.post("/user/login", async function (req, res) {
  let username = req.body.username;
  let password = req.body.password;
  if (username === "" || password === "")
    return res.json({
      code: 400,
      message: "Account or password cannot be empty",
    });

  let user = await User.findOne({ where: { username } });
  if(!user){
    return res.json({ code: 4002, message: "用户不存在!" });
  }
  if (user.state === 0) {
    return res.json({ code: 4003, message: "用户已禁用,请联系管理员!" });
  }

  // 密码加密比较
  let md5Pass = md5(req.body.password + req.body.username);
  if (user.password === md5Pass) {
    let data = await vertoken.setToken(user.username, user.id);
    return res.json({
      code: 200,
      message: "login success",
      data: { token: data },
    })
  }
  return res.json({ code: 400, message: "密码错误" });
});

/**
 * 添加用户接口
 * @api {POST} /user/add 添加用户接口
 * @apiDescription 添加用户接口
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {String} username="admin"         用户名(登录名)
 * @apiBody {String} nickname="admin"         昵称
 * @apiBody {String} username="17695479222"   手机号
 * @apiBody {String} password="123456"        密码
 * @apiBody {String} avatar="http://xxx.jpg"  头像
 * @apiBody {Number} role_id=1                角色id
 * @apiBody {Number} state=1                  状态 1 启用 0 禁用
 * @apiParamExample {json} Request-Example:
 *     {
 *        "username": "admin",
 *        "nickname": "管理员",
 *        "mobile": "17695479222",
 *        "avatar": "http://xxx.jpg",
 *        "password": "123456",
 *        "role_id": 1,
 *        "state": 1
 *     }
 * @apiGroup User
 * @apiVersion 1.0.0
 */
router.post("/user/add", async function (req, res) {
  try {
    let { username, nickname, avatar, mobile, password, state, role_id } =
      req.body;
    // 查询用户名是否重复
    let user = await User.findOne({ where: { username } });
    console.log("用户是否存在:", user);

    if (user) {
      return res.json({ code: 500, message: "用户已经存在" });
    }
    password = md5(req.body.password + req.body.username);
    let time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    let result = await User.create({
      username,
      nickname,
      avatar,
      password,
      mobile,
      state,
      role_id,
      create_time: time,
      updated_time: time,
    });
    console.log("添加用户成功", result);
    return res.json({ code: 200, message: "success" });
  } catch (err) {
    return res.json({
      code: 500,
      message: "fail:" + err,
    });
  }
});

/**
 * 编辑用户接口
 * @api {POST} /user/edit 编辑用户接口
 * @apiDescription 编辑接口
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   id
 * @apiBody {String} nickname="管理员"              昵称
 * @apiBody {String} avatar="http://xxx.jpg"       头像
 * @apiBody {String} mobile="17695479222"          手机号
 * @apiBody {String} password="123456"             密码
 * @apiBody {Number} state=1                       状态 1 启用 0 禁用
 * @apiBody {Number} role_id=1                     角色id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "nickname": "管理员",
 *        "avatar": "http://xxx.jpg",
 *        "mobile": "17695479322",
 *        "password": "123456",
 *        "role_id": 1,
 *        "state": 1
 *     }
 * @apiGroup User
 * @apiVersion 1.0.0
 */
router.post("/user/edit", async function (req, res) {
  try {
    let { id, username, nickname, avatar, mobile, password, state, role_id } =
      req.body;
    if (!id) {
      return res.send({ code: 500, msg: "缺少id参数" });
    }
    let one = await User.findOne({
      where: {
        id,
      },
    });
    console.log("查询用户数据", one);
    if (!one) {
      return res.json({ code: 500, message: "用户不存在" });
    }
    let data = one.dataValues;
    if (username) {
      data.username = username;
    }
    if (nickname) {
      data.nickname = nickname;
    }
    if (avatar) {
      data.avatar = avatar;
    }
    if (password) {
      data.password = md5(password + data.username);
    }
    if (mobile) {
      data.mobile = mobile;
    }
    if (state == 0 || state == 1) {
      data.state = state;
    }
    if (role_id) {
      data.role_id = role_id;
    }

    data.updated_time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    console.log("用户保存数据", data);

    let result = await User.update(data, {
      where: {
        id,
      },
    });
    console.log("编辑用户:", result);
    return res.json({ code: 200, message: "编辑成功" });
  } catch (err) {
    return res.json({
      code: 500,
      message: "编辑失败:" + err,
    });
  }
});

/**
 * 分页查询用户接口
 * @api {POST} /user/queryUserByPage 分页查询用户接口
 * @apiDescription 分页查询用户接口
 * @apiName queryUserByPage
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiBody {String} username  用户名
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "size": "10"
 *     }
 * @apiGroup User
 * @apiVersion 1.0.0
 */
router.post("/user/queryUserByPage", async function (req, res) {
  page = req.body.page;
  limit = req.body.limit;
  let offset = (page - 1) * limit;
  let where = {};
  if (req.body.username) {
    where["username"] = {
      [Op.like]: "%" + req.body.username + "%",
    };
  }
  try {
    const result = await User.findAndCountAll({
      attributes: [
        `id`,
        `username`,
        `nickname`,
        `mobile`,
        `role_id`,
        `created_time`,
        `state`,
        `avatar`,
        `updated_time`,
      ],
      where,
      order: [["created_time", "DESC"]],
      limit,
      offset,
    });
    return res.json({ code: 200, message: "success", data: result });
  } catch (error) {
    console.log(error);
    return res.json({ code: -1, message: error });
  }
});

/**
 * @api {POST} /user/bindRole 绑定角色
 * @apiDescription 绑定角色
 * @apiName bindRole
 * @apiGroup User
 * @apiBody {String} user_ids="1,2,3" 用户ids
 * @apiBody {Number} role_id=1 角色id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "user_ids": "1,2,3",
 *        "role_id": 1
 *     }
 * @apiVersion 1.0.0
 */
router.post("/user/bindRole", async (req, res) => {
  try {
    let { user_ids, role_id } = req.body;
    if (!user_ids || !role_id) return res.send({ code: 500, msg: "缺少参数" });

    let user_id_arr = user_ids.split(",");
    console.log("用户id", user_id_arr, " 角色id", role_id);
    let users = await User.findAll({
      where: {
        id: {
          [Op.in]: user_id_arr,
        },
      },
    });
    console.log("查询角色数据", users);
    if (users.length === 0)
      return res.json({ code: 500, message: "用户不存在" });

    let time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    for (let i = 0; i < users.length; i++) {
      let user = users[i].dataValues;
      console.log("user:===>", user);
      let result = await User.update(
        {
          role_id,
          updated_time: time,
        },
        {
          where: {
            id: user.id,
          },
        }
      );
      console.log("绑定角色:", result);
    }
    return res.json({ code: 200, message: "绑定角色成功" });
  } catch (err) {
    return res.json({
      code: 500,
      message: "绑定角色失败:" + err,
    });
  }
});

/**
 * @api {POST} /user/profile 查询用户信息
 * @apiDescription 查询用户信息
 * @apiName profile
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiGroup User
 * @apiParamExample {json} Request-Example:
 *     {
 *     }
 * @apiVersion 1.0.0
 */
router.post("/user/profile", async (req, res) => {
  if (!req.data.user_id) {
    return res.send(fail("缺少参数"));
  }
  // 查询用户信息
  let user = (await User.findByPk(req.data.user_id)).dataValues;
  if (!user) {
    return res.send(fail("用户数据异常"));
  }
  user.password = "";
  // 查询角色信息
  let role = (await Role.findByPk(user.role_id)).dataValues;
  if (!role) {
    return res.json({ code: 200, message: "角色信息不存在!" });
  }
  return res.json(
    successWithData({ role: role, ...user, permission: { menu: [] } })
  );
});

module.exports = router;
